import json
import subprocess
import uuid

import biliBV
import ffmpy3 as ffmpy3
from django.http import JsonResponse
from django.utils import timezone
from course.models import *
# from olivebranch.settings import FFPROBE_PATH, FFMPEG_PATH
from olivebranch.settings import HOST_NAME
from user.models import *


def get_duration_from_ffmpeg(url):
    tup_resp = ffmpy3.FFprobe(
        inputs={url: None},
        global_options=[
            '-v', 'quiet',
            '-print_format', 'json',
            '-show_format', '-show_streams'
        ]
    ).run(stdout=subprocess.PIPE)

    meta = json.loads(tup_resp[0].decode('utf-8'))
    return meta['format']['duration']


# def get_cover_from_ffmpeg(url, name):
#     path = urlsplit(url).netloc
#     print(path)
#     ffmpy3.FFmpeg(executable=FFMPEG_PATH, inputs={url: None}, global_options=[
#         '-y', '-f', 'image2', '-frames', '1', + name + ".jpg"
#     ]).run(stdout=subprocess.PIPE)
#     return name + ".jpg"

# def get_cover_from_ffmpeg(in_file):
#     probe = ffmpeg.probe(in_file)
#     video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
#     frame_num = int(video_stream['nb_frames'])
#
#     out, err = (
#         ffmpeg.input(in_file)
#             .filter('select', 'gte(n,{})'.format(frame_num))
#             .output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
#             .run(capture_stdout=True)
#     )
#     return out


# Create your views here.
class CourseView:
    @staticmethod
    def add(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            name = data.get("name")
            mTeamID = data.get("mTeamID")
            teamsID = data.getlist("teamsID")
            info = data.get("info")
            image = request.FILES.get("image")
            sTime = data.get("sTime")
            eTime = data.get("etime")
            if name is not None and mTeamID is not None and sTime is not None and eTime is not None:
                newCourseObj = Course.objects.create(name=name, startTime=sTime, endTime=eTime, manageTeam_id=mTeamID,
                                                     info=info, image=image)
                for teamID in teamsID:
                    if Team.objects.filter(id=teamID).first() is None:
                        return JsonResponse({
                            "code": 1,
                            "message": "Check Failed"
                        })
                newCourseObj.teams.set(teamsID)
                newCourseObj.save()
                return JsonResponse({
                    "code": 0,
                    "data": {
                        "id": newCourseObj.id
                    }
                })
            else:
                return JsonResponse({
                    "code": 1,
                    "message": "error parameters"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def dlt(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get('id')
            if Course.objects.filter(id=id).first() is not None:
                delCourseObj = Course.objects.get(id=id)
                delCourseObj.delete()
                return JsonResponse({
                    "code": 0,
                    "message": "success"
                })
            else:
                return JsonResponse({
                    "code": 1,
                    "message": "ID not found"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def mod(request):
        if request.method == "POST":
            # data = json.loads(request.body)
            data = request.POST
            id = data.get("id")
            teamsID = data.get("teamsID")
            info = data.get("info")
            image = request.FILES.get("image")
            sTime = data.get("sTime")
            eTime = data.get("etime")
            if Course.objects.filter(id=id).first() is not None:
                modCourseObj = Course.objects.get(id=id)
                modCourseObj.info = info
                modCourseObj.image = image
                modCourseObj.sTime = sTime
                modCourseObj.eTime = eTime
                modCourseObj.teams.set(teamsID)
                modCourseObj.save()
                return JsonResponse({
                    "code": 0,
                    "message": "success"
                })
            else:
                return JsonResponse({
                    "code": 1,
                    "message": "ID not found"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def search(request):
        if request.method == "POST":
            data = request.POST
            keyword = data.get("keyword")
            courseObjs = Course.objects.filter(name__icontains=keyword)
            courseIDList = []
            for courseObj in courseObjs:
                courseIDList.append(courseObj.id)
            return JsonResponse({
                "code": 0,
                "data": {
                    "list": courseIDList,
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def join(request):
        if request.method == "POST":
            # data = json.loads(request.body)
            data = request.POST
            id = data.get("id")
            userID = data.get("userID")
            courseObj = Course.objects.filter(id=id).first()
            userObj = User.objects.filter(id=userID).first()
            userInfoObj = UserInfo.objects.get(user_id=userID)
            nowTime = timezone.now()
            # nowTime = datetime.datetime.now().replace(tzinfo=pytz.timezone('Asia/Shanghai'))
            if userObj is not None and courseObj is not None and userInfoObj is not None:
                courseObj = Course.objects.get(id=id)
                userInfoObj = UserInfo.objects.get(user_id=userID)
                if userInfoObj.courses.filter(id=id).first() is not None:
                    return JsonResponse({
                        "code": 1,
                        "message": "already joined"
                    })
                if nowTime > courseObj.startTime and nowTime < courseObj.endTime:
                    userInfoObj.courses.add(id)
                    userInfoObj.save()
                    return JsonResponse({
                        "code": 0,
                        "message": "success"
                    })
                else:
                    return JsonResponse({
                        "code": 3,
                        "message": "not in time range"
                    })
            else:
                return JsonResponse({
                    "code": 1,
                    "message": "error parameters"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def info(request):
        if request.method == "POST":
            # data = json.loads(request.body)
            data = request.POST
            id = data.get("id")
            print(id)
            print(type(id))
            courseObj = Course.objects.filter(id=id).first()
            if courseObj is not None:
                # teamsIDList = []
                # for team in courseObj.teams.all():
                #     teamsIDList.append(team.id)
                return JsonResponse({
                    "code": 1,
                    "data": {
                        "name": courseObj.name,
                        "info": courseObj.info,
                        "image": HOST_NAME + "/media/" + courseObj.image.name,
                        "addTime": courseObj.addTime,
                        "eTime": courseObj.endTime,
                        "sTime": courseObj.startTime,
                        "mTeam": courseObj.manageTeam.id,
                        "teams": [i.id for i in courseObj.teams.all()],
                    }
                })
            else:
                return JsonResponse({
                    "code": 1,
                    "message": "ID not found"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def list(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            type = data.get("type")
            # order = data.get("order")
            list = []
            if type == '0':  # 全部
                courseObjs = Course.objects.all().order_by('id')
                for courseObj in courseObjs:
                    data = {
                        "id": courseObj.id,
                        "name": courseObj.name,
                        "info": courseObj.info,
                        "image": HOST_NAME + "/media/" + courseObj.image.name,
                        "addTime": courseObj.addTime,
                        "eTime": courseObj.endTime,
                        "sTime": courseObj.startTime,
                        "mTeam": courseObj.manageTeam.id,
                        "teams": [i.id for i in courseObj.teams.all()],
                    }
                    list.append(data)
            elif type == '1':  # 进行中
                nowTime = timezone.now()
                # nowTime = datetime.datetime.now().replace(pytz.timezone('Asia/Shanghai'))
                courseObjs = Course.objects.filter(startTime__lt=nowTime, endTime__gt=nowTime).order_by('id')
                for courseObj in courseObjs:
                    data = {
                        "id": courseObj.id,
                        "name": courseObj.name,
                        "info": courseObj.info,
                        "image": HOST_NAME + "/media/" + courseObj.image.name,
                        "addTime": courseObj.addTime,
                        "eTime": courseObj.endTime,
                        "sTime": courseObj.startTime,
                        "mTeam": courseObj.manageTeam.id,
                        "teams": [i.id for i in courseObj.teams.all()],
                    }
                    list.append(data)
            return JsonResponse({
                "code": 0,
                "data": {
                    "list": list
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def quit(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get("id")
            userID = data.get("userID")
            courseObj = Course.objects.filter(id=id).first()
            userObj = User.objects.filter(id=userID).first()
            userInfoObj = UserInfo.objects.get(user_id=userID)
            if userObj is not None and courseObj is not None and userInfoObj is not None:
                if userInfoObj.courses.filter(id=id).first() is None:
                    return JsonResponse({
                        "code": 1,
                        "message": "not joined"
                    })
                courseObj = Course.objects.get(id=id)
                userInfoObj = UserInfo.objects.get(user_id=userID)
                userInfoObj.courses.remove(courseObj)
                userInfoObj.save()
                return JsonResponse({
                    "code": 0,
                    "message": "quit success"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def fav(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get("id")
            userID = data.get("userID")
            courseObj = Course.objects.filter(id=id).first()
            userObj = User.objects.filter(id=userID).first()
            userInfoObj = UserInfo.objects.get(user_id=userID)
            if userObj is not None and courseObj is not None and userInfoObj is not None:
                if userInfoObj.fav.filter(id=id).first() is not None:
                    return JsonResponse({
                        "code": 1,
                        "message": "already favorited"
                    })
                userInfoObj = UserInfo.objects.get(user_id=userID)
                userInfoObj.fav.add(id)
                userInfoObj.save()
                return JsonResponse({
                    "code": 0,
                    "message": "fav success"
                })
            else:
                return JsonResponse({
                    "code": 1,
                    "message": "error parameters"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def unfav(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get("id")
            userID = data.get("userID")
            courseObj = Course.objects.filter(id=id).first()
            userObj = User.objects.filter(id=userID).first()
            userInfoObj = UserInfo.objects.get(user_id=userID)
            if userObj is not None and courseObj is not None and userInfoObj is not None:
                if userInfoObj.fav.filter(id=id).first() is None:
                    return JsonResponse({
                        "code": 1,
                        "message": "not favorited"
                    })
                courseObj = Course.objects.get(id=id)
                userInfoObj = UserInfo.objects.get(user_id=userID)
                userInfoObj.fav.remove(courseObj)
                userInfoObj.save()
                return JsonResponse({
                    "code": 0,
                    "message": "unfav success"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def favList(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            userID = data.get("userID")
            userObj = User.objects.filter(id=userID).first()
            userInfoObj = UserInfo.objects.get(user_id=userID)
            if userObj is not None and userInfoObj is not None:
                favList = []
                for favCourse in userInfoObj.fav.order_by('id'):
                    favList.append(favCourse.id)
                return JsonResponse({
                    "code": 0,
                    "data": {
                        "favList": favList
                    }
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def joinList(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            userID = data.get("userID")
            userObj = User.objects.filter(id=userID).first()
            userInfoObj = UserInfo.objects.get(user_id=userID)
            if userObj is not None and userInfoObj is not None:
                joinList = []
                for joinCourse in userInfoObj.courses.order_by('id'):
                    joinList.append(joinCourse.id)
                return JsonResponse({
                    "code": 0,
                    "data": {
                        "joinList": joinList
                    }
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def teamList(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            teamID = data.get("teamID")
            # teamObj = Team.objects.filter(id=teamID).first()
            teamManCourses = Course.objects.filter(manageTeam__id=teamID)
            teamJoinCourses = Course.objects.filter(teams__id=teamID)
            manList = []
            for mc in teamManCourses:
                manList.append(mc.id)
            joinList = []
            for jc in teamJoinCourses:
                joinList.append(jc.id)
            return JsonResponse({
                "code": 0,
                "data": {
                    "joinList": joinList,
                    "manList": manList
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def listVideo(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            courseID = data.get("id")
            videoObjs = Video.objects.filter(course_id=courseID)
            vList = []
            for videoObj in videoObjs:
                videoData = {}
                videoInfo = {}
                videoInfo['type'] = videoObj.type
                if videoObj.type in [3]:
                    videoInfo['startTime'] = videoObj.startTime
                    videoInfo['endTime'] = videoObj.endTime
                videoInfo['title'] = videoObj.title
                videoInfo['image'] = HOST_NAME + "/media/" + videoObj.image.name
                videoInfo['uploadTime'] = videoObj.uploadTime
                videoInfo['uploadUser'] = videoObj.uploadUser.id
                videoInfo['text'] = videoObj.text
                if videoObj.type in [2]:
                    videoInfo['size'] = videoObj.size
                videoData['id'] = videoObj.id
                videoData['info'] = videoInfo
                vList.append(videoData)
            return JsonResponse({
                "code": 0,
                "data": {
                    "vList": vList
                }
            })

        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def listIssue(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            courseID = data.get("id")
            issueObjs = Issue.objects.filter(courseTo_id=courseID)
            iList = []
            for issueObj in issueObjs:
                issueData = {}
                issueInfo = {}
                issueInfo['text'] = issueObj.text
                issueInfo['status'] = issueObj.status
                issueInfo['starterTo'] = issueObj.starterTo
                issueInfo['startTime'] = issueObj.startTime
                issueInfo['lastReplyTime'] = issueObj.lastReplyTime
                issueData['id'] = issueObj.id
                issueData['info'] = issueInfo
                iList.append(issueData)
            return JsonResponse({
                "code": 0,
                "data": {
                    "iList": iList
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def listComment(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            courseID = data.get("id")
            commentObjs = Comment.objects.filter(courseTo_id=courseID)
            cList = []
            for commentObj in commentObjs:
                commentData = {}
                commentInfo = {}
                commentInfo['user'] = commentObj.user.id
                commentInfo['username'] = commentObj.user.username
                commentInfo['addTime'] = commentObj.addTime
                commentInfo['text'] = commentObj.text
                commentData['id'] = commentObj.id
                commentData['info'] = commentInfo
                cList.append(commentData)
            return JsonResponse({
                "code": 0,
                "data": {
                    "iList": cList
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })


class CommentView:
    @staticmethod
    def add(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            courseID = data.get("courseID")
            id = data.get("id")
            text = data.get("text")
            newCommentObj = Comment.objects.create(user_id=id, courseTo_id=courseID, text=text)
            newCommentObj.save()
            return JsonResponse({
                "code": 0,
                "data": {
                    "id": newCommentObj.id
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def dlt(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            commentID = data.get("commentID")
            if Comment.objects.filter(id=commentID).first() is None:
                return JsonResponse({
                    "code": 2,
                    "message": "评论ID不存在"
                })
            dltCommentObj = Comment.objects.get(id=commentID)
            dltCommentObj.delete()
            dltCommentObj.save()
            return JsonResponse({
                "code": 0,
                "data": {
                    "id": commentID
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def mod(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            commentID = data.get("commentID")
            text = data.get("text")
            modCommentObj = Comment.objects.get(id=commentID)
            modCommentObj.text = text
            modCommentObj.save()
            return JsonResponse({
                "code": 0,
                "data": {
                    "id": commentID
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })


class VideoView:
    @staticmethod
    def add(request):
        if request.method == "POST":
            data = request.POST
            title = data.get('title')
            userID = data.get('id')
            courseID = data.get('courseID')
            type = int(data.get('type'))
            imageFile = request.FILES.get('image')
            fileName = uuid.uuid4().hex
            if imageFile is not None:
                imageext = os.path.splitext(imageFile.name)[1]
                imageFile.name = str(fileName + imageext)
            if type == 0:
                BVID = data.get('BVID')
                page = data.get('page')
                videoObj = Video.objects.create(uploadUser_id=userID, BVID=BVID, course_id=courseID, title=title,
                                                type=type, page=page)
                if imageFile is not None:
                    videoObj.image = imageFile
                videoObj.save()
                return JsonResponse({
                    "code": 0,
                    "data": {
                        "vid": videoObj.id
                    }
                })
            elif type == 1:
                url = data.get('url')
                videoObj = Video.objects.create(uploadUser_id=userID, url=url, course_id=courseID, title=title,
                                                type=type)
                if imageFile is not None:
                    videoObj.image = imageFile
                videoObj.save()
                return JsonResponse({
                    "code": 0,
                    "data": {
                        "vid": videoObj.id
                    }
                })
            elif type == 2:
                videoFile = request.FILES.get('video')
                videoext = os.path.splitext(videoFile.name)[1]
                videoFile.name = str(fileName + videoext)
                videoObj = Video.objects.create(uploadUser_id=userID, video=videoFile, course_id=courseID, title=title,
                                                size=videoFile.size)
                # print(path)
                path = videoObj.video.path
                duration = get_duration_from_ffmpeg(path)
                videoObj.duration = duration
                if imageFile is not None:
                    videoObj.image = imageFile
                videoObj.save()
                return JsonResponse({
                    "code": 0,
                    "data": {
                        "url": HOST_NAME + "/media/" + videoObj.video.name,
                        "vid": videoObj.id
                    }
                })
            elif type == 3:
                startTime = data.get('startTime')
                endTime = data.get('endTime')
                url = data.get('url')
                videoObj = Video.objects.create(uploadUser_id=userID, course_id=courseID, title=title,
                                                startTime=startTime, url=url, endTime=endTime)
                if imageFile is not None:
                    videoObj.image = imageFile
                videoObj.save()
            else:
                return JsonResponse({
                    "code": 2,
                    "message": "type should in [0,1,2,3]"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def dlt(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get('id')
            if Video.objects.filter(id=id).first() is not None:
                videoObj = Video.objects.get(id=id)
                videoObj.delete()
                videoObj.save()
                return JsonResponse({
                    "code": 0,
                })
            else:
                return JsonResponse({
                    "code": 1,
                    "message": "id not found"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def geturl(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get('id')
            if Video.objects.filter(id=id).first() is not None:
                videoObj = Video.objects.get(id=id)
                if videoObj.type == 0:
                    return JsonResponse({
                        "code": 0,
                        "data": {
                            "type": 0,
                            "url": "https://www.bilibili.com/video/" + videoObj.BVID,
                            "BVID": videoObj.BVID,
                            "AVID": biliBV.decode(videoObj.BVID),
                            "page": videoObj.page,
                            "bili_player": "http://player.bilibili.com/player.html?bvid=" + videoObj.BVID + "&amp;high_quality=1&amp;danmaku=0&amp;as_wide=1",
                            "bili_h5player": "https://www.bilibili.com/blackboard/html5player.html?bvid=" + videoObj.BVID + "&page=" + str(
                                videoObj.page) + "&as_wide=1",
                        }
                    })
                elif videoObj.type in [1, 3]:
                    return JsonResponse({
                        "code": 0,
                        "data": {
                            "type": videoObj.type,
                            "url": videoObj.url,
                        }
                    })
                elif videoObj.type == 2:
                    return JsonResponse({
                        "code": 0,
                        "data": {
                            "type": 2,
                            "url": HOST_NAME + "/media/" + videoObj.video.name,
                        }
                    })
            else:
                return JsonResponse({
                    "code": 2,
                    "message": "video does not exist"
                })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def info(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get('id')
            if Video.objects.filter(id=id).first() is not None:
                videoObj = Video.objects.get(id=id)
                response = {"id": id,
                            "uploadUser": videoObj.uploadUser_id,
                            "uploadTime": videoObj.uploadTime,
                            "size": videoObj.size,
                            "duration": videoObj.duration,
                            "title": videoObj.title,
                            "image": HOST_NAME + "/media/" + videoObj.image.name, }
                if videoObj.type == 0:
                    response['url'] = "https://www.bilibili.com/video/" + videoObj.BVID,
                    response['BVID'] = videoObj.BVID
                    response['AVID'] = biliBV.decode(videoObj.BVID)
                    response['bili_player'] = "http://player.bilibili.com/player.html?bvid=" + videoObj.BVID + \
                                              "&amp;high_quality=1&amp;danmaku=0&amp;as_wide=1"
                    response['bili_h5player'] = "https://www.bilibili.com/blackboard/html5player.html?bvid=" \
                                                + videoObj.BVID + "&page=" + str(videoObj.page) + "&as_wide=1"
                elif videoObj.type == 1:
                    response['url'] = videoObj.url
                elif videoObj.type == 2:
                    response['url'] = HOST_NAME + "/media/" + videoObj.video.name
                elif videoObj.type == 3:
                    response['startTime'] = videoObj.startTime
                    response['endTime'] = videoObj.endTime
                    response['url'] = videoObj.url
                return JsonResponse({
                    "code": 0,
                    "data": response
                })
            else:
                return JsonResponse({
                    "code": 1,
                    "message": "id not found"
                })

        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })


class IssueView:
    @staticmethod
    def add(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            courseID = data.get('id')
            courseObj = Course.objects.filter(id=courseID).first()
            if courseObj is None:
                return JsonResponse({
                    "code": 2,
                    "message": "课程不存在"
                })
            text = data.get('text')
            title = data.get('title')
            startUserID = data.get('uid')
            userObj = User.objects.filter(id=startUserID).first()
            if userObj is None:
                return JsonResponse({
                    "code": 2,
                    "message": "用户不存在"
                })
            newIssueObj = Issue.objects.create(text=text, courseTo_id=courseID, starterTo_id=startUserID, title=title)
            newIssueObj.save()
            return JsonResponse({
                "code": 0,
                "data": {
                    "id": newIssueObj.id
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def mod(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get('id')
            issueObj = Issue.objects.filter(id=id).first()
            if issueObj is None:
                return JsonResponse({
                    "code": 2,
                    "message": "Issue不存在"
                })
            status = data.get('status')
            if status is not None and int(status) in [0, 1, 2]:
                issueObj.status = status
            text = data.get('text')
            title = data.get('title')
            if text is not None:
                issueObj.text = text
            if title is not None:
                issueObj.title = title
            issueObj.save()
            return JsonResponse({
                "code": 0,
                "data": {
                    "id": issueObj.id
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def get(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            id = data.get('id')
            issueObj = Issue.objects.filter(id=id).first()
            if issueObj is None:
                return JsonResponse({
                    "code": 2,
                    "message": "Issue不存在"
                })
            issueData = {}
            issueData['id'] = id
            issueData['courseTo'] = issueObj.courseTo.id
            issueData['text'] = issueObj.text
            issueData['status'] = issueObj.status
            issueData['starter'] = issueObj.starterTo.id
            issueData['startTime'] = issueObj.startTime
            issueData['lastReplyTime'] = issueObj.lastReplyTime
            return JsonResponse({
                "code": 0,
                "data": issueData
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def listReply(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            issueID = data.get('id')
            issueObj = Issue.objects.filter(id=issueID).first()
            if issueObj is None:
                return JsonResponse({
                    "code": 2,
                    "message": "Issue不存在"
                })
            replyObjs = Reply.objects.filter(issueTo_id=issueID).order_by('replyTime')
            replyList = []
            for replyObj in replyObjs:
                replyData = {}
                replyData['id'] = replyObj.id
                replyData['text'] = replyObj.text
                replyData['user'] = replyObj.userTo.id
                replyData['replyTime'] = replyObj.replyTime
                replyList.append(replyData)
            return JsonResponse({
                "code": 0,
                "data": {
                    "replyList": replyList
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })


class ReplyView:
    @staticmethod
    def add(request):
        if request.method == "POST":
            data = request.POST
            issueID = data.get('id')
            issueObj = Issue.objects.filter(id=issueID).first()
            if issueObj is None:
                return JsonResponse({
                    "code": 2,
                    "message": "issue不存在"
                })
            text = data.get('text')
            userID = data.get('uid')
            userObj = User.objects.filter(id=userID).first()
            if userObj is None:
                return JsonResponse({
                    "code": 2,
                    "message": "用户不存在"
                })
            newReplyObj = Reply.objects.create(text=text, issueTo_id=issueID, userTo_id=userID)
            newReplyObj.save()
            nowTime = timezone.now()
            # nowTime = datetime.datetime.now().replace(tzinfo=pytz.timezone('Asia/Shanghai'))
            issueObj.lastReplyTime = nowTime
            issueObj.save()
            return JsonResponse({
                "code": 0,
                "data": {
                    "id": newReplyObj.id
                }
            })
            # data = json.loads(request.body)
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def mod(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            replyID = data.get('id')
            text = data.get('text')
            if Reply.objects.filter(id=replyID).first() is None:
                return JsonResponse({
                    "code": 2,
                    "message": "回复ID不存在"
                })
            replyObj = Reply.objects.get(id=replyID)
            if text is not None:
                replyObj.text = text
            replyObj.save()
            issueObj = replyObj.issueTo
            nowTime = timezone.now()
            # nowTime = datetime.datetime.now().replace(tzinfo=pytz.timezone('Asia/Shanghai'))
            issueObj.lastReplyTime = nowTime
            issueObj.save()
            return JsonResponse({
                "code": 0,
                "data": {
                    "id": replyObj.id
                }
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })

    @staticmethod
    def get(request):
        if request.method == "POST":
            data = request.POST
            # data = json.loads(request.body)
            replyID = data.get('id')
            if Reply.objects.filter(id=replyID).first() is None:
                return JsonResponse({
                    "code": 2,
                    "message": "回复ID不存在"
                })
            replyObj = Reply.objects.get(id=replyID)
            replyData = {}
            replyData['id'] = replyObj.id
            replyData['text'] = replyObj.text
            replyData['user'] = replyObj.userTo.id
            replyData['replyTime'] = replyObj.replyTime
            return JsonResponse({
                "code": 0,
                "data": replyData
            })
        else:
            return JsonResponse({
                "code": 2,
                "message": "error method"
            })
